// pages/batch/batch.js
var util = require('../../database/data.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tid: '',
    cit: '',
    cont_num: 2,
    page_num: 0,
    sms_num: 63,
    signaNum: 0,
    showDialog: false,
    showCenterDialog: true,
    canvasClose:true,
    showAlert: true,
    isShow: true,
    // showLogin: true,
    sendOrder: false
  },

  //弹窗
  onClickdiaCenterView: function(e) {
    this.setData({
      showCenterDialog: !this.data.showCenterDialog,
      showDialog: !this.data.showDialog
    })
  },

  batchSubmit: function(e) {
    var classId = e.currentTarget.dataset.classid;
    wx.showLoading({
      title: "订单生成中",
      mask: true,
    });
    switch (classId) {
      case '0':
        var contData = this.data.contData;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: 10067,
          cid: contData.cid,
          tid: contData.tid,
          openId: this.data.userId,
          contact: this.data.phoneHidden,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: contData.content.replace(/(^\s*)|(\s*$)/g, ""),
        };
        this.submitSendData(api, sendData);
        break;
      case '1':
        var contData = this.data;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: 10067,
          cid: '0',
          tid: '0',
          openId: this.data.userId,
          contact: this.data.phoneHidden,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: contData.content,
        };
        this.submitSendData(api, sendData);
        break;
    }
  },
  //获取用户手机号
  getPhoneNumber: function(e) {
    let that = this;
    var classId = e.currentTarget.dataset.classid;
    //session_key 未过期，并且在本生命周期一直有效
    var sessionKey = that.data.sessionKey;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.request({
        url: app.globalData.smsbaoApi + '/batch/sapi/decryptData',
        method: "post",
        data: {
          sessionKey: sessionKey,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function(res) {
          var phone = res.data.data;
          var userPhone = JSON.parse(phone);
          wx.setStorageSync('userInfo', userPhone.phoneNumber)
          that.onBatchSubmit(classId, userPhone.phoneNumber);
        }
      })
    } else {
      var userPhone = 0;
      that.onBatchSubmit(classId, userPhone);
    }
  },
  //数据提交
  onBatchSubmit: function(classId, contact) {
    wx.showLoading({
      title: "订单生成中",
      mask: true,
    });
    switch (classId) {
      case '0':
        var contData = this.data.contData;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: '10067',
          cid: contData.cid,
          tid: contData.tid,
          openId: this.data.userId,
          contact: contact,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: contData.content.replace(/(^\s*)|(\s*$)/g, ""),
        };
        this.submitSendData(api, sendData);
        break;
      case '1':
        var contData = this.data;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: '10067',
          cid: '0',
          tid: '0',
          openId: this.data.userId,
          contact: contact,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: contData.content,
        };
        this.submitSendData(api, sendData);
        break;
    }

  },

  //发送短信到服务器
  submitSendData: function(url, data) {
    let that = this;
    wx.request({
      url: url,
      method: "post",
      data: {
        appId: data.appId,
        cid: data.cid,
        tid: data.tid,
        openId: data.openId,
        contact: data.contact,
        phone: data.sendPhone,
        sign: data.sign,
        content: data.content
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.data.code == '200') {
          setTimeout(function() {
            wx.hideLoading()
          }, 1000)
          that.ProcessingReturnData(res, data);
          that.setData({
            orderId: res.data.data.orderId,
            showAlert: false,
          })

        } else {
          wx.showToast({
            title: '网络超时',
            icon: 'loading',
            duration: 1500
          })
          var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId';
          that.wxlogin(getOpenid);
        }

      },
      fail: function(error) {
        console.log(error)
      }
    })
  },
  //接受返回数据生成订单
  ProcessingReturnData: function(orderId, data) {
    // 调用函数时，传入new Date()参数，返回值是日期和时间  
    var time = util.formatTime(new Date());
    var orderId = orderId.data.data.orderId;
    var orderData = wx.getStorageSync("order");
    var orderInfoData = [];
    for (var i in orderData) {
      orderInfoData.push(orderData[i])
    }
    var orderInfo = {
      orderId: orderId,
      tid: data.tid,
      cid: data.cid,
      phone: data.sendPhone,
      sign: data.sign,
      time: time,
      content: data.content
    };
    orderInfoData.push(orderInfo);
    wx.reportAnalytics('add_order', {
      add_order: orderId,
      add_time: time,
    });
    wx.setStorageSync('order', orderInfoData);
  },
  //短信内容的实时数量
  signaNum: function(e) {
    var num = e.detail.value.length;
    this.setData({
      signaNum: num
    })
  },
  textNum: function(e) {
    var upd_num = e.detail.value.length;
    var page_upd_num = Math.ceil(upd_num / this.data.sms_num);
    this.setData({
      cont_num: upd_num + 2,
      page_num: page_upd_num,
    })
  },
  //获取openid
  wxlogin: function(url) {
    let that = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          // //发起网络请求
          wx.request({
            url: url,
            method: "post",
            data: {
              code: res.code
            },
            success: function(res) {
              if (res.data.code == '200') {
                that.setData({
                  userId: res.data.data.openId,
                  sessionKey: res.data.data.session_key
                })
                wx.hideNavigationBarLoading();
              } else {
                wx.showToast({
                  title: '网络超时',
                  icon: 'loading',
                  duration: 1500
                })
                var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId'
                that.wxlogin(getOpenid)
              }

            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //从缓存获取用户手机号
    var userPhone = wx.getStorageSync("userInfo");
    if (userPhone) {
      this.setData({
        phoneHidden: userPhone
      })
    };
    wx.showNavigationBarLoading();
    var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId'
    this.wxlogin(getOpenid)

    switch (options.class) {
      case '0':
        var contData = JSON.parse(options.data);
        var contents = contData.content;
        var start = contents.indexOf("【");
        var end = contents.indexOf("】");
        var sign = contents.substring(start + 1, end);
        var cont = contents.substring(end + 1);
        //获取文本的数量
        var num = contents.length;
        var pag_num = Math.ceil(num / this.data.sms_num);
        this.setData({
          contData: contData,
          cid: contData.cid,
          tid: contData.tid,
          sign: sign,
          content: cont,
          cont_num: num + 2,
          page_num: pag_num,
          classId: options.class
        })
        break;
      case '1':
        //获取文本的数量
        var contData = JSON.parse(options.data);
        var start = contData.indexOf("【");
        var end = contData.indexOf("】");
        var sign = contData.substring(start + 1, end);
        var cont = contData.substring(end + 1);
        var num = contData.length;
        var pag_num = Math.ceil(num / this.data.sms_num);
        this.setData({
          sign: sign,
          content: cont,
          cont_num: num + 2,
          page_num: pag_num,
          classId: options.class
        })
        break;
    }
    wx.hideNavigationBarLoading();
  },
  //手机号验
  removeEmptyArrayEle: function(arr) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == undefined && arr[i] == null || arr[i] == "") {
        arr.splice(i, 1);
        i = i - 1; // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位，
        // 这样才能真正去掉空元素,觉得这句可以删掉的连续为空试试，然后思考其中逻辑
      }
    }
    return arr;
  },
  //正则验证手机号
  isPoneAvailable: function(e) {
    var phone = e.detail.value.split("\n");
    var phones = this.removeEmptyArrayEle(phone);
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    for (var i = 0; i < phones.length; i++) {
      if (!myreg.test(phones[i])) {
        wx.showToast({
          title: '手机号格式不正确',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      }
    }
    this.setData({
      sendPhone: phones
    })
  },
  //第一次提交
  onSubmit: function(e) {
    if (e.type == 'submit') {
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (e.detail.value.phone == '') {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      if (e.detail.value.signature == '') {
        wx.showToast({
          title: '输入3-8个字符的短信签名',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      if (e.detail.value.content == '') {
        wx.showToast({
          title: '请输入短信内容',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      switch (e.detail.target.dataset.status) {
        case '1':
          this.setData({
            showCenterDialog: !this.data.showCenterDialog,
            showDialog: !this.data.showDialog,
            upContent: e.detail.value.content,
            signature: e.detail.value.signature,
            sendPhone: this.data.sendPhone,
            showLogin: !this.data.showLogin
          });
          break;
      }
    }
  },
  //电话热线
  onMakePhone: function(e) {
    wx.makePhoneCall({
      phoneNumber: '400-716-3021',
    })
  },
  contact: function(e) {
    wx.navigateTo({
      url: "contact_kefu/contact_kefu",
    })
  },

  onContentShare: function(e) {
    let that = this;
    var cid = e.currentTarget.dataset.cid;
    var tid = JSON.stringify(e.currentTarget.dataset.tid);    
    const wxCanvasToTempFilePath = util.wxPromisify(wx.canvasToTempFilePath);
    const wxSaveImageToPhotosAlbum = util.wxPromisify(wx.saveImageToPhotosAlbum);
    var res = wx.getSystemInfoSync()
    //bgk图
    var dWidth = Math.ceil(res.windowWidth * 0.8);
    var dHeight = Math.ceil(res.windowHeight * 0.8);
    //canvas的X,Y
    var sWidth = Math.ceil(res.windowWidth - dWidth) / 2;
    var sHeight = 30;
    //二维码的X , Y
    var canvasWidth = dWidth - 60 + sWidth;
    var canvasHeight = dHeight - 60;
    //内容的X,Y
    var fillX = Math.ceil(dWidth / 2);
    var fillY = Math.ceil(dHeight / 4) + sHeight;
    this.setData({
      cid: cid,
      tid: tid,
      isShow: false,
      showDialog: !this.data.showDialog,
      canvasClose: true,
      dWidth: res.windowWidth + "px",
      dHeight: dHeight + "px"
    });
    //   // 使用 wx.createContext 获取绘图上下文 context    
    var ctx = wx.createCanvasContext('shareCanvas');
    var text = "奇思妙想的短信内容,创意十足的短信模板";
    ctx.drawImage("/images/banner/share_img.png", sWidth, sHeight, dWidth, dHeight);
    ctx.drawImage("/images/banner/1530762585.png", canvasWidth, canvasHeight, 60, 60);
    ctx.drawImage("/images/banner/logo.png", sWidth, sHeight, 120, 60);
    ctx.setTextAlign('center');
    ctx.setFontSize(15);
    ctx.setFillStyle("#ffffff");
    ctx.fillText("奇思妙想的短信内容", fillX, fillY);
    ctx.setTextAlign('left');
    ctx.fillText("创意十足的短信模板", fillX, fillY + 20);
    ctx.setTextAlign('center');
    ctx.setFontSize(10);
    ctx.fillText("扫码查看更多行业经典短信内容", fillX, dHeight-5);

    ctx.stroke()
    ctx.draw()
    setTimeout(function() {
      wxCanvasToTempFilePath({
        x: sWidth,
        y: sHeight,
        width: dWidth,
        height: dHeight,
        canvasId: 'shareCanvas'
      }, this).then(res => {
        return wxSaveImageToPhotosAlbum({
          filePath: res.tempFilePath
        })
      }).then(res => {
        wx.showToast({
          title: '已保存到相册'
        })
        that.setData({
          canvasClose: !that.data.canvasClose,
        })
      }).catch()
    }, 1000);

  },
  onClose: function (e) {
    this.setData({
      isShow: !this.data.isShow,
      showDialog: !this.data.showDialog,
    })

  },
})